#!/usr/bin/env python3
import os
import sys

if len(sys.argv) < 1:
    print('Usage: {} <bin> [xxx.c]')
    exit(1)

bin_path = sys.argv[1]
bin_base = os.path.basename(bin_path)

c_base = bin_base.replace('.', '_').lower()
c_path = os.path.join(os.path.dirname(bin_path), c_base + '.c')
if len(sys.argv) > 2:
    c_path = sys.argv[2]

bin_len, bin_data = 0, []
print('Reading {} ...'.format(bin_path))
with open(bin_path, 'rb') as bin_fd:
    bin_data = bin_fd.read()
    bin_len = len(bin_data)

print('Generate {} ...'.format(c_path))
with open(c_path, 'w+') as c_fd:
    cols = 32
    c_fd.write('/* THIS FILE IS GENERATED BY {}, DO NOT EDIT IT! */\n'.format(os.path.basename(__file__)))
    c_fd.write('#define {}_size {}\n'.format(c_base, bin_len))
    c_fd.write('const char {}_name[] = "{}";\n'.format(c_base, bin_base))
    c_fd.write('const unsigned char {}_data[] = {{\n'.format(c_base))
    for i in range(bin_len):
        if i % cols == 0:
            c_fd.write('  ')
        c_fd.write('0x{:02x},'.format(bin_data[i]))
        if (i + 1) % cols != 0:
            c_fd.write(' ')
        else:
            c_fd.write('\n')
    if bin_len % cols != 0:
        c_fd.write('\n')
    c_fd.write('};\n')
print('Done!')

